import matlab.engine
import numpy as np
import os

try:
    # 启动MATLAB引擎
    print("启动MATLAB引擎...")
    eng = matlab.engine.start_matlab()
    
    # 加载已保存的MATLAB神经网络模型
    print("加载MATLAB模型...")
    model_path = r'D:\PyCharm\project\Deep-DeePC\_results\threetanks\44\model\matlab.mat'
    eng.load(model_path, nargout=0)
    
    # 获取MATLAB工作区中的变量
    print("检查MATLAB工作区变量...")
    workspace_vars = eng.eval('whos', nargout=1)
    print("MATLAB工作区变量:", workspace_vars)
    
    # 获取神经网络的输入大小
    print("获取神经网络输入大小...")
    input_size = eng.eval("net.inputs{1}.size", nargout=1)
    print(f"神经网络输入大小: {input_size}")
    
    # 准备输入数据
    print("准备输入数据...")
    input_data = np.array([7.331072092056274414e-01,3.812441527843475342e-01,8.887692689895629883e-01,7.331072092056274414e-01,3.812441527843475342e-01,8.887692689895629883e-01,7.331072092056274414e-01,3.812441527843475342e-01,8.887692689895629883e-01,7.331072092056274414e-01,3.812441527843475342e-01,8.887692689895629883e-01,7.331072092056274414e-01,3.812441527843475342e-01,8.887692689895629883e-01,7.331072092056274414e-01,3.812441527843475342e-01,8.887692689895629883e-01,7.331072092056274414e-01,3.812441527843475342e-01,8.887692689895629883e-01,7.331072092056274414e-01,3.812441527843475342e-01,8.887692689895629883e-01,7.331072092056274414e-01,3.812441527843475342e-01,8.887692689895629883e-01,7.331072092056274414e-01,3.812441527843475342e-01,8.887692689895629883e-01,1.612207770347595215e+00,-1.483004808425903320e+00,5.104247480630874634e-02,5.830991864204406738e-01,6.577450633049011230e-01,3.687949478626251221e-01,5.263608694076538086e-01,5.271645784378051758e-01,5.350694656372070312e-01,5.404440164566040039e-01,5.297995209693908691e-01,5.432512760162353516e-01,5.515853166580200195e-01,5.412709116935729980e-01,5.525483489036560059e-01,5.624194145202636719e-01,5.520957112312316895e-01,5.628319382667541504e-01,5.729454159736633301e-01,5.624883174896240234e-01,5.730386972427368164e-01,5.830215215682983398e-01,5.723993182182312012e-01,5.829105377197265625e-01,5.925853252410888672e-01,5.817905068397521973e-01,5.923278927803039551e-01,6.016123294830322266e-01,5.906490087509155273e-01,6.012366414070129395e-01,0.000000000000000000e+00,0.000000000000000000e+00,0.000000000000000000e+00,7.949233055114746094e-03,7.801771163940429688e-03,7.852315902709960938e-03])
    
    # 确保输入数据形状正确
    input_size_py = int(input_size)
    if len(input_data) != input_size_py:
        print(f"警告：输入数据长度 {len(input_data)} 与神经网络期望的输入大小 {input_size_py} 不匹配")
        # 如果长度不匹配，可以截断或填充数据
        if len(input_data) > input_size_py:
            input_data = input_data[:input_size_py]
            print(f"已截断输入数据至长度 {input_size_py}")
        else:
            # 填充数据
            padding = np.zeros(input_size_py - len(input_data))
            input_data = np.concatenate([input_data, padding])
            print(f"已填充输入数据至长度 {input_size_py}")
    
    # 转换为MATLAB格式的列向量
    matlab_input = matlab.double(input_data.reshape(-1, 1).tolist())
    print(f"输入数据形状: {matlab_input.size}")
    
    # 使用神经网络进行预测
    print("使用神经网络进行预测...")
    # 将输入数据传递到MATLAB工作区
    eng.workspace['matlab_input'] = matlab_input
    # 直接调用神经网络
    output = eng.eval("net(matlab_input)", nargout=1)
    print("预测成功!")
    
    # 将输出转换回Python格式
    try:
        # 尝试标准方式转换
        python_output = np.array(output._data).reshape(output.size, order='F')
        print("预测结果:")
        print(python_output)
    except Exception as e:
        print(f"标准转换方式失败: {e}")
        try:
            # 尝试直接转换
            python_output = np.array(output)
            print("使用直接转换方式")
            print("预测结果:")
            print(python_output)
        except Exception as e:
            print(f"所有转换方式都失败: {e}")
            print("原始输出类型:", type(output))
            if hasattr(output, '__dict__'):
                print("输出属性:", output.__dict__)
            print("原始输出:", output)
    
    # 关闭MATLAB引擎
    eng.quit()
    print("MATLAB引擎已关闭")
    
except Exception as e:
    print(f"发生错误: {e}")
    # 确保在出错时也关闭MATLAB引擎
    try:
        eng.quit()
        print("MATLAB引擎已关闭")
    except:
        pass